#!/bin/bash

if [ -z $RUNNER ]; then
    # docker or podman
    RUNNER="docker"
fi

echo "RUNNER: ${RUNNER}"

GIT_ROOT=$(git rev-parse --show-toplevel)

if [ -z "$1" ]; then
    VERSION=$(yq .Version ${GIT_ROOT}/configuration/build_config.yaml)
else
    VERSION=$1
fi
CONTAINER_NAME=$(yq '.["Base-Name"]' ${GIT_ROOT}/configuration/build_config.yaml)
REPO_NAME=$(yq .Repository ${GIT_ROOT}/configuration/build_config.yaml)
CONTAINER_IMAGE="${REPO_NAME}/${CONTAINER_NAME}:${VERSION}"

if [ -z "$IMAGES" ]; then
    mkdir -p images
    IMAGES="$PWD/images"
fi

echo "Using images from ${IMAGES}."

if [ -z "$RESULTS" ]; then
    mkdir -p results
    RESULTS="$PWD/results"
fi

echo "Using ${RESULTS} as result folder."

if [ -z "$WORKSPACE" ]; then
    mkdir -p images
    WORKSPACE=$PWD
fi

echo "Using workspace from ${WORKSPACE}."

# Test if docker image is available
if [ -z "$(docker images -q ${CONTAINER_IMAGE})" ]; then
    # Build the container.
    ${GIT_ROOT}/builder/build_container
else
    echo "Dev container image ${CONTAINER_IMAGE} is available."
fi

echo "CONTAINER_NAME: ${CONTAINER_NAME}"

lsmod | grep binfmt_misc > /dev/null
if [ $? -ne 0 ]; then
    echo "Trying to load binfmt kernel module for cross-builds ..."
    sudo modprobe binfmt_misc
fi

echo "Stopping and deleting the container..."
$RUNNER stop $CONTAINER_NAME 2>&1 1>/dev/null | true
$RUNNER rm $CONTAINER_NAME 2>&1 1>/dev/null | true

echo "Running the container..."
$RUNNER run --rm -it \
    --name $CONTAINER_NAME \
    -u ebcl \
    -v ${HOME}/.ssh:/home/ebcl/.ssh:ro \
    -v ${RESULTS}:/build/results:rw \
    -v ${IMAGES}:/build/images:rw \
    -v ${WORKSPACE}:/workspace:rw \
    -v /dev:/dev \
    --privileged \
    --init \
    ${CONTAINER_IMAGE}
